package com.ruoyi.quartz.controller;


import cn.hutool.http.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.quartz.domain.PhoneNumber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.AlgorithmParameters;
import java.security.Security;



@Controller
public class HomeController {

    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.secret}")
    private String secret;


//    @Anonymous
//    @PostMapping("/oauth")
//    @ResponseBody
//    public String wxOauth(@RequestParam("code") String code) throws Exception{
//        System.out.println("=====12341234========");
//        System.out.println(code);
//        Object res = getPhoneNumber(code);
//        return res.toString();
//    }


    @Anonymous
    @PostMapping("/oauth")
    @ResponseBody
    public Object getPhoneNumber(@RequestBody PhoneNumber phoneNumber) {
        System.out.println(phoneNumber.getCode());
        String result = null;
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
            String replaceUrl = url.replace("{0}", appid).replace("{1}", secret);
            String res = HttpUtil.get(replaceUrl);
            JSONObject json_token = JSON.parseObject(res);
            String access_token = json_token.getString("access_token");

            String urlTwo = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={0}";
            String replaceUrlTwo = urlTwo.replace("{0}",access_token);
            HashMap<String, Object> requestParam = new HashMap<>();
            // 手机号调用凭证
            requestParam.put("code", phoneNumber.getCode());
            String jsonStr = JSON.toJSONString(requestParam);
            HttpResponse response = HttpRequest.post(replaceUrlTwo)
                    .header(Header.CONTENT_ENCODING, "UTF-8")
                    // 发送json数据需要设置contentType
                    .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .body(jsonStr)
                    .execute();

            if (response.getStatus() == HttpStatus.HTTP_OK) {
                result = response.body();
            }
            System.out.println(result);
        } catch (HttpException e) {
            e.printStackTrace();
        }
        return JSONObject.parseObject(result).get("phone_info");
    }



}